package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {

    @Value("${reggie.path}")
    private String Path;

    @PostMapping("/upload")
    public R upload(MultipartFile file)  {
        //原始文件名
        String originalFilename = file.getOriginalFilename();
        //截取文件后缀
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //UUID 生成文件名
        String uuid = UUID.randomUUID().toString();
        File dir = new File(Path);
        //如果目录不存在就创建
        if (!dir.exists()) {
            dir.mkdirs();
        }


        try {
            //将文件存入指定文件夹
            file.transferTo(new File(Path, uuid + suffix));
        } catch (IOException e) {
            e.printStackTrace();
        }
        //返回文件名
        return R.success(uuid + suffix);
    }

    @GetMapping("/download")
    public void download(String name , HttpServletResponse response)  {
        try {
            //输入流获取图片
            FileInputStream fileInputStream = new FileInputStream(new File(Path,name));
            //输出流写回浏览器
            ServletOutputStream outputStream = response.getOutputStream();
            //两个流读写工具类
            IOUtils.copy(fileInputStream,outputStream);
            //关闭流
            fileInputStream.close();
            outputStream.close();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }
}
